package com.xiaomili.halfsugar.activity;

import android.content.ContentResolver;
import android.database.Cursor;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.xiaomili.halfsugar.R;
import com.xiaomili.halfsugar.adapter.PopAdapter;
import com.xiaomili.halfsugar.app.IApp;
import com.xiaomili.halfsugar.bean.ImageBean;
import com.xiaomili.halfsugar.fragment.PicFragment;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2016/7/24 0024.
 */
public class PicActivity extends AppCompatActivity {
    @InjectView(R.id.tv_pop)
    TextView tvPop;
    @InjectView(R.id.tv_all)
    TextView tvAll;
    @InjectView(R.id.iv_all)
    ImageView ivAll;
    private static final int SCAN_OK = 1;
    private ImageBean mImageBean;
    private ListView lv;
    private List<ImageBean> list = new ArrayList<>();
    private PopAdapter adapter;
    private Toolbar toolbar;
    private PopupWindow popupWindow;
    private List<String> childList;
    private HashMap<String, List<String>> mGruopMap = new HashMap<String, List<String>>();
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SCAN_OK:
                    adapter = new PopAdapter(getApplicationContext(), subGroupOfImage(mGruopMap));
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pic);
        ButterKnife.inject(this);
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.container_host, new PicFragment());
        ft.commit();
        popupWindow = new PopupWindow();
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        getImages();
    }

    private void getImages() {
//        mDatas = new ArrayList<>();
        // mProgressDialog = ProgressDialog.show(this,null,"正在加载...");
        new Thread(new Runnable() {
            @Override
            public void run() {
                Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ContentResolver mContentResolver = PicActivity.this.getContentResolver();
                Cursor mCursor = mContentResolver.query(mImageUri, null, MediaStore.Images.Media.MIME_TYPE + "=? or "
                                + MediaStore.Images.Media.MIME_TYPE + "=?",
                        new String[]{"image/jpeg", "image/png"}, MediaStore.Images.Media.DATE_MODIFIED);
                if (mCursor == null) {
                    return;
                }
                while (mCursor.moveToNext()) {
                    //获取图片的路径
                    String path = mCursor.getString(mCursor
                            .getColumnIndex(MediaStore.Images.Media.DATA));

                    //获取该图片的父路径名
                    String parentName = new File(path).getParentFile().getName();
                    System.out.println(parentName);
                    //根据父路径名将图片放入到mGruopMap中
                    if (!mGruopMap.containsKey(parentName)) {
                        List<String> chileList = new ArrayList<String>();
                        chileList.add(path);
                        mGruopMap.put(parentName, chileList);
                    } else {
                        mGruopMap.get(parentName).add(path);
                    }
                }
                mCursor.close();
                mHandler.sendEmptyMessage(SCAN_OK);
            }
        }).start();
    }

    private List<ImageBean> subGroupOfImage(HashMap<String, List<String>> mGroupMap) {
        if (mGroupMap.size() == 0) {
            return null;
        }
        List<ImageBean> list = new ArrayList<>();
        Iterator<Map.Entry<String, List<String>>> it = mGroupMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, List<String>> entry = it.next();
            mImageBean = new ImageBean();
            String key = entry.getKey();
            List<String> value = entry.getValue();

            mImageBean.setFolderName(key);
            Log.i("tag","value"+value.size());
            mImageBean.setImageCounts(value.size());
            mImageBean.setTopImagePath(value.get(0));
            list.add(mImageBean);
        }
        return list;
    }

    @OnClick({R.id.tv_pop, R.id.tv_all, R.id.iv_all})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_pop:
                finish();
                break;
            case R.id.tv_all:
                if (popupWindow==null){
                    showPopUpWindow();
                }if (popupWindow.isShowing()){
                    popupWindow.dismiss();
                }else{
                    popupWindow.showAsDropDown(toolbar);
                    popupWindow.update();
                }
                break;
            case R.id.iv_all:
                showPopUpWindow();
                break;
        }
    }

    private void showPopUpWindow() {
            popupWindow.setWidth(IApp.mScreenWidth);
            popupWindow.setHeight((IApp.mScreenHeight / 4) * 3);
            View view = this.getLayoutInflater().inflate(R.layout.popupwindow, null);
//            lv = (ListView) view.findViewById(R.id.lv);
//            //adapter = new PopAdapter(PublishActivity.this,list = subGroupOfImage(mGruopMap));
//            lv.setAdapter(adapter);
//            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//                @Override
//                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                    childList = mGruopMap.get(list.get(position).getFolderName());
//                    Log.i("dididi","child.size"+childList.size());
//                    Intent intent = new Intent(PicActivity.this,ShowImageActivity.class);
//                    intent.putStringArrayListExtra("data",(ArrayList<String>)childList);
//                    startActivity(intent);
//                }
//            });
            popupWindow.setContentView(view);
            popupWindow.setFocusable(true);
            popupWindow.setOutsideTouchable(true);
            popupWindow.setBackgroundDrawable(new ColorDrawable());
            popupWindow.setTouchInterceptor(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_OUTSIDE){
                        popupWindow.dismiss();
                        return true;
                    }
                    return false;
                }
            });
            popupWindow.showAsDropDown(toolbar);
    }


    public int getStatusHeight() {
        int height = 0;
        int resId;  //获取状态栏变量对应的地址
        //1.先通过变量名找地址,通过地址取地址的内容
        //因为status_bar_height是私有的,无法直接获取内容
        resId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        //String packageName = context.getPackageName();
        //int resIdDrawable = getResources().getIdentifier("ic_launcher","drawable",packageName);
        if (resId > 0) {
            //通过地址获取高度
            height = getResources().getDimensionPixelOffset(resId);
        }
        Log.i("123", "状态栏的高度-->" + height);
        return height;
    }
}
